﻿using Microsoft.Extensions.Hosting;
using Project.Core.Config.Common.Utils;
using System.Diagnostics;

namespace Project.Core.Config.Config.Mq {
    public class InitialService : IHostedService, IDisposable {
        private readonly IMqConnectionHelper MqConnection;

        public InitialService(IMqConnectionHelper mqConnection) {
            this.MqConnection = mqConnection;
        }

        public Task StartAsync(CancellationToken cancellationToken) {
            InitRabbitMQConnection(); // 创建RabbitMQ的连接
            return Task.CompletedTask;
        }

        private void InitRabbitMQConnection() {
            // 读取配置信息
            MqConnectionHelper.MqConfig = AppHelper.ReadAppSettings<MqConfigInfo>("Mq", new string[] { "MqConfig" });

            Debug.WriteLine("开始生产者连接");
            MqConnection.SendFactoryConnectionInit();
            MqConnection.SendFactoryConnection();

            Debug.WriteLine("生产者连接完成，开始连接消费者");
            MqConnection.ReceiveFactoryConnectionInit();
            for (int i = 0; i < MqConnectionHelper.CostomerCount; i++) {
                MqConnection.ConnectionReceive(i, MqConnectionHelper.MqConfig.FirstOrDefault().ExchangeName, MqConnectionHelper.RoutingKey[i], MqConnectionHelper.QueueName[i]);
            }

            //Debug.WriteLine("生产者连接完成，准备发送消息");
            //MqConnectionHelper.PublishExchange("Hello,MQ~~", MqConnectionHelper._mqConfig.FirstOrDefault().ExchangeName, MqConnectionHelper._routingKey[0]);
            //MqConnectionHelper.PublishExchange("Hello,MQ~~", MqConnectionHelper._mqConfig.FirstOrDefault().ExchangeName, MqConnectionHelper._routingKey[1]);
            Debug.WriteLine("消费者连接完成，生产者准备发送消息");
            for (int i=0;i< 100;i++) {
                if (i % 2 == 0) {
                    MqConnectionHelper.PublishExchange("Hello,MQ~~", MqConnectionHelper.MqConfig.FirstOrDefault().ExchangeName, MqConnectionHelper.RoutingKey[0]);
                } else {
                    MqConnectionHelper.PublishExchange("Hello,MQ~~", MqConnectionHelper.MqConfig.FirstOrDefault().ExchangeName, MqConnectionHelper.RoutingKey[1]);
                }
                //Thread.Sleep(500);
            }

            Debug.WriteLine("消息发送完成");
        }

        public Task StopAsync(CancellationToken cancellationToken) {
            return Task.CompletedTask;
        }

        public void Dispose() {
            throw new NotImplementedException();
        }
    }
}
